package com.usian.wemedia.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.apis.wemedia.MaterialManageControllerApi;
import com.usian.apis.wemedia.WmMaterialControllerApi;
import com.usian.common.constants.wemedia.WemediaContans;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.service.impl.WmMaterialServiceImpl;
import com.usian.wemedia.service.impl.WmUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/material")
public class WmMaterialController implements WmMaterialControllerApi, MaterialManageControllerApi {
@Autowired
private WmMaterialServiceImpl wmMaterialService;
    @Autowired
    FastDFSClient fastDFSClient;


    @Value("${fdfs.url}")
    private String fileServerUrl;


    @PostMapping("/upload_picture")
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if(multipartFile == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //String s="[{\"type\":\"text\",\"value\":\"howareyou随着智能手机的普及，人们更加习惯于通过手机来看新闻。由于生活节奏的加快，很多人只能利用碎片时间来获取，因此，对于移动资讯客户端的需求也越来越高。积云头条项目正是在这样背景下开发出来。积云头条项目采用当下火热微服务+大数据技术架构实现。本项目主要着手于获取最新最热新闻资讯，通过大数据分析用户喜好精确推送咨询新\"},{\"type\":\"image\",\"value\":\"http://192.168.58.138/group1/M00/00/00/wKg6imKpbneAOuNzAABRu3GIT74159.png\"}]";

        //2.上传图片到fasfdfs
        String fileId = null;
        try {
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //3.保存素材数据到表中 wm_material

        Integer userId = WmThreadLocalUtils.getUserId();

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setUserId(userId);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterialService.save(wmMaterial);
        //拼接图片路径
        wmMaterial.setUrl(fileServerUrl+fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    @RequestMapping("/list")
    public ResponseResult findList(WmMaterialDto dto) {
        //2.带条件分页查询
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取当前登录的用户
        Integer uid = WmThreadLocalUtils.getUserId();
        lambdaQueryWrapper.eq(WmMaterial::getUserId,uid);
        //是否收藏
        if(dto.getIsCollection() != null && dto.getIsCollection().shortValue()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //按照日期倒序排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage pageParam = new Page(dto.getPage(),dto.getSize());
        IPage resultPage = wmMaterialService.page(pageParam, lambdaQueryWrapper);
        //3.结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)resultPage.getTotal());
        List<WmMaterial> datas = resultPage.getRecords();
        //为每个图片加上前缀
        datas = datas.stream().map(item->{
            item.setUrl(fileServerUrl+item.getUrl());
            return item;
        }).collect(Collectors.toList());
        responseResult.setData(datas);

        return responseResult;
    }
    @GetMapping("/del_picture/{id}")
    @Override
    public ResponseResult delPicture(@PathVariable Integer id) {
        return wmMaterialService.delPicture(id);
    }

    @Override
    @GetMapping("/cancel_collect/{id}")
    public ResponseResult cancleCollectionMaterial(@PathVariable Integer id) {
        return wmMaterialService.updateStatus(id,WemediaContans.CANCEL_COLLECT_MATERIAL);
    }

    @Override
    @GetMapping("/collect/{id}")
    public ResponseResult collectionMaterial(@PathVariable Integer id) {

        return wmMaterialService.updateStatus(id,WemediaContans.COLLECT_MATERIAL);
    }
}
